import { BaseGeometry } from './basegeometry';
import { Point } from './point';

export class EllipseGeometry extends BaseGeometry {
    constructor(x: number, y: number, width: number, height: number) {
        super(x, y, width, height);
    }
    /**
     * 判断是否落在形状内
     * @param point 
     */
    public pointInThis(point: Point): boolean {
        // 圆心坐标
        const circleX = this.x + this.width / 2;
        const circleY =  this.y + this.height / 2;
        const r = this.width / 2;
        if (r === 0) return false;
        const dx = circleX - point.x;
        const dy = circleY - point.y;
        return dx * dx + dy * dy <= r * r;
    }
    /**
     * 计算线段与此几何图形的焦点
     * @param ptStart 
     * @param ptEnd 
     */
    public getIntersectPoints(ptStart: Point, ptEnd: Point): Point[] {
        const ptInter1: Point = new Point(), ptInter2: Point = new Point();
        const points: Point[] = [];
        const r = this.width / 2; // 半径
        const EPS = 0.00001;
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height / 2;
        const fDis = Math.sqrt((ptEnd.x - ptStart.x) * (ptEnd.x - ptStart.x) + (ptEnd.y - ptStart.y) * (ptEnd.y - ptStart.y));
        const d = new Point();
        d.x = (ptEnd.x - ptStart.x) / fDis;
        d.y = (ptEnd.y - ptStart.y) / fDis;
        const E = new Point();
        E.x = centerX - ptStart.x;
        E.y = centerY - ptStart.y;
        const a = E.x * d.x + E.y * d.y;
        const a2 = a * a;
        const e2 = E.x * E.x + E.y * E.y;
        if ((r - e2 + a2) < 0) {
            return points;
        } else {
            const f = Math.sqrt(r - e2 + a2);
            let t = a - f;
            if (((t - 0.0) > - EPS) && (t - fDis) < EPS) {
                ptInter1.x = ptStart.x + t * d.x;
                ptInter1.y = ptStart.y + t * d.y;
                points.push(ptInter1);
            }
            t = a + f;
            if (((t - 0.0) > -EPS) && (t - fDis) < EPS) {
                ptInter2.x = ptStart.x + t * d.x;
                ptInter2.y = ptStart.y + t * d.y;
                points.push(ptInter2);
            }

            return points;
        }
    }
}